//
//  BSearchRealm.swift
//  MySwiftObject
//
//  Created by anscen on 2022/6/1.
//  Copyright © 2022 wangws1990. All rights reserved.
//

import UIKit
import RealmSwift
fileprivate let base = BaseRealm()
class BSearch: Object {
    @Persisted var keyword    :String
    @Persisted var updateTime :TimeInterval
    @Persisted var createTime :TimeInterval
    class override func primaryKey() -> String? {
        return "keyword"
    }
}
class BSearchRealm :NSObject{
    //MARK:判断是否有数据
    fileprivate func haveData(_ keyword :String) -> Bool{
        guard let realm = base.realm else {
            return false
        }
        let some = realm.objects(BSearch.self).filter("keyword == '\(keyword)'")
        return some.count > 0 ? true : false
    }
    //MARK:有就更新没有就增加
    public func insertData(_ keyword :String){
        guard let realm = base.realm else {
            return
        }
        let haveData = haveData(keyword)
        let search = BSearch()
        search.keyword = keyword
        search.updateTime =  NSDate ().timeIntervalSince1970
        guard let _ = try? realm.write({
            if haveData{
                search.createTime = NSDate().timeIntervalSince1970
                realm.add(search, update: .all)
            }else{
                realm.add(search)
            }
        }) else { return }
    }
    //MARK:获取某一个数据
    public func getData(_ keyword :String) ->BSearch?{
        guard let realm = base.realm else {
            return nil
        }
        //查询不需要在事务中完成
        let some = realm.objects(BSearch.self).filter("keyword == '\(keyword)'")//.sorted(by: "user.userId", ascending: true)
        return some.first
    }
    //MARK:获取所有数据
    public func getDatas() ->[BSearch]?{
        guard let realm = base.realm else {
            return nil
        }
        //查询不需要在事务中完成
        let some = realm.objects(BSearch.self).sorted(byKeyPath: "updateTime", ascending: true)
        return some.reversed()
    }
    //MARK:删除指定数据
    public func deleteData(_ keyword :String){
        guard let realm = base.realm else {
            return
        }
        if let user = getData(keyword){
            try? realm.write({
                realm.delete(user)
            })
        }
    }
    //MARK:删除所有数据
    public func deleteAll(){
        guard let realm = base.realm else {
            return
        }
        try? realm.write({
            realm.deleteAll()
        })
    }
}

